package plus.xj17520.org.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import plus.xj17520.org.domain.Department;
import plus.xj17520.org.mapper.DepartmentMapper;
import plus.xj17520.org.service.IDeptService;
import plus.xj17520.base.query.DeptQuery;
import plus.xj17520.base.result.JSONResult;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @projectName: Pethome5-6
 * @package: plus.xj17520.org.service.impl
 * @className: IDeptServiceImpl
 * @author: XiaoJue
 * @description: TODO
 * @date: 2022/5/7 1:22
 * @version: 1.0
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    public JSONResult addOrUpdate(Department department) {
        if (department.getId() != null)
            departmentMapper.updateByPrimaryKey(department);
        else
            departmentMapper.insert(department);
        return JSONResult.success();
    }

    @Override
    public JSONResult findOne(Long id) {
        return JSONResult.success(departmentMapper.selectByPrimaryKey(id));
    }

    @Override
    public JSONResult findAll() {
        List<Department> departments = departmentMapper.selectAll();
        return JSONResult.success(departments);
    }

    @Override
    public JSONResult delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
        return JSONResult.success();
    }

    @Override
    public JSONResult deptPageList(DeptQuery deptQuery) {
//        Example example = new Example(Department.class);

        PageHelper.startPage(deptQuery.getCurrent(),deptQuery.getSize());
//        List<Department> departments = departmentMapper.selectByExample(example);
        List<Department> departments = departmentMapper.deptPageList(deptQuery);
        return JSONResult.success(new PageInfo<>(departments));
    }

    @Override
    public JSONResult batchDelete(DeptQuery deptQuery) {
        Long[] ids = deptQuery.getIds();
        for (Long id : ids)
            batchDeleteDeep(id);
        return JSONResult.success();
    }

    // 批量删除父节点下面的所有子节点，递归函数,非常占用内存，不推荐
    public void batchDeleteDeep(Long deptId){
        Example example = new Example(Department.class);
        example.and().andEqualTo("parentId",deptId);
        List<Department> list = departmentMapper.selectByExample(example);

        for (Department department : list){
            Long id = department.getId();
            batchDeleteDeep(id);
        }
        departmentMapper.deleteByPrimaryKey(deptId);
    }
}
